package com.gitee.huanminabc.utils_tools.web_base.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;

public class WebContextUtil {


    public static HttpServletRequest  getRequest(){
        //请求
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = ((ServletRequestAttributes) requestAttributes).getRequest();
        }
        return  request;
    }


    public static HttpServletResponse  getResponse(){
        //请求
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //响应
        HttpServletResponse response = null;
        if (requestAttributes != null) {
            response = ((ServletRequestAttributes)requestAttributes).getResponse();
        }
        return  response;
    }
    //设置当前线程的request的header
    public static void setRequestHeader(String key,String value){
        HttpServletRequest request = getRequest();
        request.setAttribute(key,value);
    }

    //读取请求体的内容 ,注意如果没有做可重复读取InputStream那么这个动作只能读取一次
    public static String getRequestString(HttpServletRequest request){
        InputStream in=null;
        ByteArrayOutputStream out=null;
        try {
            in =request.getInputStream();
            out=new ByteArrayOutputStream();
            in2OutStream(in, out, 1024*1024);
            return out.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(out !=  null)out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(in !=  null)in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    private static void in2OutStream(InputStream in, OutputStream out,
                                     int bufferSize) throws IOException {
        byte[] buffer = new byte[bufferSize];// 缓冲区
        for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;) {
            out.write(buffer, 0, bytesRead);
            Arrays.fill(buffer, (byte) 0);
        }
    }

}
